<?php

namespace App\Http\Controllers\Statistical;

use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use App\Http\Requests\Statistical\LoginRequest;
use App\Repositories\Statistical\UserRepository;
use App\Http\Requests\Statistical\UpdatePasswordRequest;
use App\Repositories\Statistical\DayStatisticsRepository;

/**
 * Class IndexController 统计首页
 *
 * @package App\Http\Controllers\Statistical
 */
class IndexController extends Controller
{
    /**
     * @var UserRepository
     */
    private $userRepository;
    /**
     * @var DayStatisticsRepository
     */
    private $dayStatisticsRepository;

    public function __construct(
        UserRepository $userRepository,
        DayStatisticsRepository $dayStatisticsRepository
    )
    {
        $this->userRepository          = $userRepository;
        $this->dayStatisticsRepository = $dayStatisticsRepository;
    }

    /**
     * 登录处理
     *
     * @param LoginRequest $request
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
     */
    public function login(LoginRequest $request)
    {
        // 已经登录直接跳转到首页
        if (session('user') && session('user.user_id')) {
            return redirect('statistical/index/index');
        }

        // 登录处理
        if ($request->isMethod('POST')) {
            // 验证数据
            $user = $this->userRepository->find([
                'username' => request()->input('username'),
                'status'   => UserRepository::STATUS_ACTIVE,
            ]);

            if (empty($user)) {
                $request->session()->flash('username', '用户名或者密码错误');
                return view('statistical.index.login');
            }

            // 验证密码
            if (!Hash::check(request()->input('password'), $user['password'])) {
                $request->session()->flash('username', '用户名或者密码错误');
                return view('statistical.index.login');
            }

            // 登录成功
            session(['user' => $user]);
            return redirect('/statistical/index/index')
                ->with('success', '登录成功');
        }

        return view('statistical.index.login');
    }

    /**
     * 首页信息
     */
    public function index()
    {
        $today_date = date('Y-m-d');
        // 接收参数
        $start_time = request()->input('start_time', $today_date) ?: $today_date;
        $end_time   = request()->input('end_time', $today_date) ?: $today_date;

        // 是否今天
        $is_today = $start_time == $end_time && $end_time == $today_date;

        // 时间交换
        if ($start_time > $end_time) {
            list($start_time, $end_time) = [$end_time, $start_time];
        }

        // 用户类型
        $user_key = session('user.type') == UserRepository::TYPE_MAIN ? 'user_id' : 'attribution_user_id';

        // 查询数据
        $data = $this->dayStatisticsRepository->find([
            'create_date:between' => [$start_time, $end_time],
            'user_id'             => session('user.' . $user_key),
        ], [
            DB::raw('SUM(success_amount) AS success_amount'),
            DB::raw('SUM(success_num) AS success_num'),
            DB::raw('SUM(not_amount) AS not_amount'),
            DB::raw('SUM(not_num) AS not_num'),
            DB::raw('SUM(user_count) AS user_count'),
            DB::raw('SUM(user_two_count) AS user_two_count'),
            DB::raw('SUM(user_three_count) AS user_three_count'),
            DB::raw('MAX(updated_at) AS updated_at'),
        ]);

        // 总数据
        $total = $this->dayStatisticsRepository->find([
            'user_id' => session('user.' . $user_key),
        ], [
            DB::raw('SUM(success_amount) AS total_success_amount'),
            DB::raw('SUM(success_num) AS total_success_num'),
            DB::raw('SUM(not_amount) AS total_not_amount'),
            DB::raw('SUM(not_num) AS total_not_num'),
        ]);

        // 总数
        $total_amount = intval(Arr::get($total, 'total_success_amount', 0) + Arr::get($total, 'total_not_amount', 0));
        $total_num    = intval(Arr::get($total, 'total_success_num', 0) + Arr::get($total, 'total_not_num', 0));

        // 今日总金额(成功充值 + 未充值)
        $today_total_amount = intval(Arr::get($data, 'success_amount', 0) + Arr::get($data, 'not_amount', 0));
        // 今日总笔数(成功 + 未充值)
        $today_total_num = intval(Arr::get($data, 'success_num', 0) + Arr::get($data, 'not_num', 0));

        return view('statistical.index.index', compact(
            'data', 'today_total_amount', 'today_total_num',
            'total_amount', 'total_num', 'total',
            'start_time', 'end_time', 'is_today'
        ));
    }

    /**
     * 设置密码
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\View\View
     */
    public function setting()
    {
        return view('statistical.index.setting');
    }

    /**
     * @param UpdatePasswordRequest $request
     *
     * @return \Illuminate\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     * @throws \Littlebug\Repository\Exception
     */
    public function updatePassword(UpdatePasswordRequest $request)
    {
        $this->userRepository->update([
            'user_id' => session('user.user_id'),
        ], ['password' => $request->input('password')]);

        return redirect('statistical/index/setting')->with('success', '修改密码成功');
    }

    /**
     * 用户退出
     *
     * @return \Illuminate\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function logout()
    {
        session()->forget('user');
        return redirect('statistical/index/login');
    }
}